package com.bto.solar.work.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 王小波
 * @description:  代理转发到sto服务
 * @date 2023/10/10 17:23
 */
@Slf4j
@RestController
@RequestMapping("/sto/**")
public class StoProxyController {

    @Value("${bto.sto-proxy-url}")
    private String stoProxyUrl;

    /**
     * 代理所sto有请求
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping()
    public String proxy(HttpServletRequest request) {
        try {
            URI uri = new URI(request.getRequestURI());
            String path = uri.getPath();
            String query = request.getQueryString();
            String target = stoProxyUrl + path;
            if (query != null && !query.isEmpty() && !query.equals("null")) {
                target = target + "?" + query;
            }
            String httpBody = IOUtils.toString(request.getInputStream(), "utf-8");
            //请求方法
            String methodName = request.getMethod();
            Method method = Method.valueOf(methodName);
            if (method == null) {
                throw new BizException("请求方法为空");
            }

            HttpRequest httpRequest = new HttpRequest(target);
            httpRequest.setMethod(method);


            Enumeration<String> headerNames = request.getHeaderNames();
            Map<String, String> headMap = new HashMap<>();
            // 设置请求头
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                Enumeration<String> v = request.getHeaders(headerName);
                List<String> arr = new ArrayList<>();
                while (v.hasMoreElements()) {
                    arr.add(v.nextElement());
                }
                headMap.put(headerName, arr.toString());
            }
            String authorization = ServletUtils.getHeader(ServletUtils.getRequest(), "Authorization");
            httpRequest.header("Authorization", authorization);
            httpRequest.body(httpBody);
            return httpRequest.execute().body();
        }
        catch (Exception e) {
            throw new BizException("sto 请求代理失败 {} " , e.getMessage());
        }

    }


}


